<template>
    <van-loading v-if="isLoading" type="spinner" />
   <van-icon
      v-else
      :color="isCollect ? '#3296fa':'#777'"
      :name="isCollect ? 'star':'star-o'"
      @click="collectHandler"
    />
</template>
<script>
import {
  addArticleCollect,
  deleteArticleCollect
} from '@/api/article'
import { mapGetters } from 'vuex'
  export default {
    name: 'CollectArticle',
    model:{
      prop:'isCollect',
      event:'update-collect'
    },
    props: {
      // 文章是否被收藏
      // value:{
      isCollect:{
        type:Boolean,
        required:true
      },
      // 文章id
      articleId:{
        type:[String,Number],
        required:true
      }
    },
    data () {
      return {
          isLoading:false // 是否加载中  
      }
    },
    computed: {
      ...mapGetters(['token'])
    },
    methods: {
      // 收藏、取消收藏事件
      async  collectHandler(){
        if(!this.token) return this.$toast.fail('请登录后操作')
        this.isLoading = true
        try {
          if(this.isCollect){
            // 收藏了，要取消
            await deleteArticleCollect(this.articleId)
          }else{
            // 未收藏，要收藏
            await addArticleCollect({
              target:this.articleId
            })
          }
          this.$toast.success('操作成功')
          this.$emit('update-collect',!this.isCollect)
        } catch (error) {
          console.log(error);
           this.$toast.fail('操作失败')
        }
        this.isLoading = false
      }
    },
    created () {},
    mounted () {},
  }
</script>
<style   scoped>
</style>